<?php

class ShoppingCart extends MX_Controller {
	function __construct()
	{
		$this->load->library('cart');
		parent::__construct();
	}
	
	function index()
	{
		if((modules::run('login/is_logged_in') == false))
		{
			if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
				echo OUT_OF_SESSION;
				exit(0);
			}else{
				$this->session->set_userdata('refered_from','shoppingcart');
				redirect('login');
			}
			return;
		}
		
		$this->load->model("model/membership_model");
		$data = $this->membership_model->populdateBuyerSignupInfo();
		//$this->membership_model->getCreditCardData($data);        
		$content = $this->load->view('shoppingcart_view', $data, true);
		Template::display($content);
	}
	
	function add(){
		
		$deal_id = $this->input->post('deal_id');
        $deal_id = base64_decode($deal_id);
        $deal_id = str_replace('deal_','', $deal_id);
        
		$deal = $this->public_model->getDealById($deal_id);
		//$processing_fee_percent = $this->public_model->getSystemParameterValue("processing_fee_percent");
		//if(empty($processing_fee_percent)) $processing_fee_percent = 10;
		
		$data = array(
           'id'      => $deal->id,
           'qty'     => 1,
           'price'   => $deal->payment_price,
           'name'    => $deal->deal_name,
           //'point'   => $product->point,
           //'processing_fee'   => round($product->point * $processing_fee_percent / 100, 2),
           'image_path'    => $deal->picture2,
           //'shipping_fee'    => $deal->shipping_fee,
           'options' => null
        );
		$this->cart->insert($data); 
	}
	function checkout(){
		$this->load->model("shoppingcart_model");
		
		$this->load->library('form_validation');
		
		$response = new stdClass(); 
        $response->success = false;
		$response->content = '';
		$response->message = null;
		$response->commonResponse = new stdClass();
		
		//validation
        $type_pay = $this->input->post('pay');
        if ($type_pay == PAYPAL)
        {   
            $this->form_validation->set_rules('pp_account', 'Email Paypal', 'required|valid_email');
            $this->form_validation->set_rules('pp_email_received', 'Email Receive', 'required|valid_email'); 
        }
        else
        {
            
        }
		
		$validation = $this->form_validation->run($this);
		if($validation == FALSE)
		{
            //$response->commonResponse->errorDescription = "Check your info.";
			$content = $this->load->view('shoppingcart_view', null,true);
			$response->content = $content;
		}else{
            $total_prices = 0;
    		if(count($this->cart->contents())>0){
    			foreach($this->cart->contents() as $item){
    				$total_prices += $item['price'] * $item['qty'];
    			}
    		}
				
            //insert order data
			$order_data = array(
                "customer_id" => $this->session->userdata('id'),
                "emailpp" => $this->input->post('pp_account'),
                "emailrecived" => $this->input->post('pp_email_received'),
                "payment_amount" => $total_prices,
                "payment_status" => ORDER_WAITING,
                "timepayment" => '0000-00-00 00:00:00',
                "transaction_id" => '-1',
                "item_number" => strtoupper(substr(md5(time().$this->session->userdata('id')),0,5)),
                "type_payment" => ($type_pay==PAYPAL)?PAYPAL:CC,
    		);
			$this->db->insert('k_orders', $order_data);
            
			$order_id = $this->db->insert_id();
            
            
            //insert orderdetail data
			foreach($this->cart->contents() as $item){
				$orderdetail_data = array(
                    "order_id" => $order_id,
                    "dealname" => $item['name'],
					"deal_id" => $item['id'],
					"price" => $item['price'],
                    "deal_code" => 'sadasd',
                );
                $this->db->insert('k_order_detail', $orderdetail_data);
			}
			$response->success = true;
			$this->cart->destroy();
			
            if ($type_pay == PAYPAL)
            {
                # Get Paypal info
                $is_sandbox = ($this->public_model->getSystemParameterValue('paypal_is_sandbox')=='true')?true:false;
                $paypal = array(
                    'IPN' => ($is_sandbox)?$this->public_model->getSystemParameterValue('paypal_sandbox_ipn'):$this->public_model->getSystemParameterValue('paypa_ipn'),
                    'live' => ($is_sandbox)?$this->public_model->getSystemParameterValue('paypal_sandbox_live'):$this->public_model->getSystemParameterValue('paypal_live'),
                    'is_sandbox' => $is_sandbox,
                    'email_business' => $this->public_model->getSystemParameterValue('paypal_email_business'),
                );
                
                $return_url = base_url()."/shoppingcart/receipt/".$order_id. "/".$this->shoppingcart_model->getOrderAccessCode($order_id);
                $cancel_url = base_url();
                $notify_url = base_url();
                
                $querystring = '';
                // Firstly Append paypal account to querystring
                $querystring .= "?business=".urlencode($paypal['email_business'])."&";    
                    
                $item_name = $this->public_model->getSystemParameterValue('websiteURL');
                $item_name .= " - Your Order ID: ".$order_id;
                
                //The item name and amount can be brought in dynamically by querying the $_POST['item_number'] variable.
                $querystring .= "item_name=".urlencode($item_name)."&";    //order name
                $querystring .= "item_number=".urlencode(stripslashes($order_data['item_number']))."&";   //order detail
                $querystring .= "amount=".urlencode($order_data['payment_amount'])."&";
                     
                     
                $querystring .= "cmd=".urlencode(stripslashes('_xclick'))."&";
                $querystring .= "no_note=".urlencode(stripslashes('1'))."&";
                     $querystring .= "lc=".urlencode(stripslashes('US'))."&";
                     $querystring .= "currency_code=".urlencode(stripslashes('CAD'))."&";
                     //$querystring .= "handling=".urlencode(stripslashes('0'))."&";
                     //$querystring .= "bn=".urlencode(stripslashes('PP-BuyNowBF:btn_buynow_LG.gif:NonHostedGuest'))."&";
                     //$querystring .= "first_name=".urlencode(stripslashes('Customer First Name'))."&";
                     //$querystring .= "last_name=".urlencode(stripslashes('Customer Last Name'))."&";
                    //$querystring .= "no_shipping=".urlencode(stripslashes($order_data['payment_amount']))."&";
                    
                     // Append paypal return addresses
                     $querystring .= "return=".urlencode(stripslashes($return_url))."&";
                     $querystring .= "cancel_return=".urlencode(stripslashes($cancel_url))."&";
                     $querystring .= "notify_url=".urlencode($notify_url);
                    
                // Append querystring with custom field
                //$querystring .= "&custom=".USERID;
                    
                   
                // Redirect to paypal IPN
                //header('location:'.$paypal['IPN'].$querystring);
                $response->content = '';
                $response->url_paypal = $paypal['IPN'].$querystring;
            }
            else
            {
    			//load receipt page
    			$response->content = '';
                $order_data = array("access_code" => $this->shoppingcart_model->getOrderAccessCode($order_id));
    			$order_data['id'] = $order_id;
    			$response->order_data = $order_data;        
            }
		}
		echo json_encode($response);
	}
	function checkout_2(){
		$this->load->model("model/membership_model");
		$this->load->model("shoppingcart_model");
		
		$this->load->library('form_validation');
		
		$response = new stdClass(); 
        $response->success = false;
		$response->content = '';
		$response->message = null;
		$response->commonResponse = new stdClass();
		
		//validation
		$this->form_validation->set_rules('firstname', 'First Name', 'trim|required|max_length[100]');
		$this->form_validation->set_rules('lastname', 'Last Name', 'trim|required|max_length[100]');
		$this->form_validation->set_rules('address1', 'Address 1', 'trim|required|max_length[255]');
		$this->form_validation->set_rules('address2', 'Address 2', 'max_length[255]');
		$this->form_validation->set_rules('city', 'City', 'trim|required');
		$this->form_validation->set_rules('state', 'State', '');
		$this->form_validation->set_rules('stateText', 'State', '');
		$this->form_validation->set_rules('country', 'Country', '');
		$this->form_validation->set_rules('zip', 'Shipping Zip', 'required|max_length[9]|numeric|min_length[5]|');
		$this->form_validation->set_rules('phone1', 'Shipping Phone 1', 'exact_length[3]|numeric');
		$this->form_validation->set_rules('phone2', 'Shipping Phone 2', 'callback_validatephone');
		$this->form_validation->set_rules('phone3', 'Shipping Phone 3', 'max_length[5]|numeric');
		
//		$this->form_validation->set_rules('biCountry', 'Country', '');

		//$this->form_validation->set_rules('paymentName', 'Card holder Name', 'trim|required|max_length[100]');
		//$this->form_validation->set_rules('paymentNumber', 'Card Number', 'trim|required|max_length[16]|min_length[16]');
//		$this->form_validation->set_rules('paymentCVV2Code', 'CVV Code', 'trim|required|max_length[4]');
//		$this->form_validation->set_rules('biAddress1', 'Address 1', 'trim|required|max_length[255]');
//		$this->form_validation->set_rules('biaddress2', 'Address 2', 'max_length[255]');
//		$this->form_validation->set_rules('biCity', 'City', 'trim|required');
//		$this->form_validation->set_rules('biState', 'State', '');
//		$this->form_validation->set_rules('biStateText', 'State', '');
//
//		$this->form_validation->set_rules('biCountry', 'Country', '');
//		$this->form_validation->set_rules('biZip', 'Shipping Zip', 'required|max_length[9]|numeric|min_length[5]|');
//		$this->form_validation->set_rules('biPhone1', 'Shipping Phone 1', 'exact_length[3]|numeric');
//		$this->form_validation->set_rules('biPhone2', 'Shipping Phone 2', 'callback_validatephone');
//		$this->form_validation->set_rules('biPhone3', 'Shipping Phone 3', 'max_length[5]|numeric');
		
		
		
		$total_point = 0;
		$total_fee = 0;
		$shipping_fee = 0;
		$processing_fee_percent = $this->public_model->getSystemParameterValue("processing_fee_percent");
		if(empty($processing_fee_percent)) $processing_fee_percent = 10;
		if(count($this->cart->contents())>0){
			foreach($this->cart->contents() as $item){
				$total_point += $item['point'] * $item['qty'];
				$total_fee += $item['processing_fee'] * $item['qty'];
				$shipping_fee += $item['shipping_fee'] * $item['qty'];
			}
		}
		//$shipping_fee = round($processing_fee_percent * $total_point / 100, 2);
		$total_point += $shipping_fee + $total_fee;
		
		$validation = $this->form_validation->run($this);
		$current_balance = modules::run('game/getCurrentBalance');
		if($current_balance < $total_point){
			$validation = false;
		}
				
		if($validation == FALSE)
		{
			if($current_balance < $total_point){
				$response->commonResponse->errorDescription = 'Your current balance is not enough to exchange.';
			}
			$data = $this->membership_model->populdateBuyerSignupInfo();
			$this->membership_model->getCreditCardData($data);
			$content = $this->load->view('shoppingcart_view', $data,true);
			$response->content = $content;
		}else{
			
//			$this->load->library('payment');
//			$paymentobj = new payment();
//			
//			$first_last_name = $this->public_model->getFirstLastName($this->input->post('paymentName'));
//			$creditCardInfo = array('cardNum' => $paymentobj->encrypt($this->input->post('paymentNumber')),
//							'creditCardLast4Digits'=>substr($this->input->post('paymentNumber'),strlen($this->input->post('paymentNumber'))-4,4),
//							'expYear' => $this->input->post('paymentExpireYear'),
//							'expMonth' => $this->input->post('paymentExpireMonth'),
//							'cardCodePresent' => 'ValuePresent',
//							'cardCode' => $this->input->post('paymentCVV2Code'), 
//							'cardholderFirstName' => $first_last_name[0],
//							'cardholderLastName' => $first_last_name[1],
//							'cardHolderCompanyName' => null,
//							'cardHolderFullName' => $first_last_name[0]. " ". $first_last_name[1],																
//							'track1' => null,
//							'track2' => null,
//							'streetAddressLine1' => $this->input->post('biAddress1'),
//							'zip' => $this->input->post('biZip'),
//							'ext' => '',									
//							'cardType' => $this->input->post('paymentCardType'), 
//							'entryMode' => 'Manual',
//							'signature' => null,
//							'cardPresent' => 'NO',								
//						);						
//			$request = array("creditCardInfo" => $creditCardInfo,
//									   "amount" => $total_fee,
//									   "paymentAccountId" => 0,
//									   "action" => "payment");
//			$response = $paymentobj->makePayment($request);
			
			//if($response->success){
//				$data = $this->membership_model->populdateBuyerSignupInfo();
//				$this->membership_model->getCreditCardData($data);
//				//substract point
//				modules::run('pay/exchangePointToItem', $this->session->userdata('id'), $total_point);				
//				//insert billing and shipping address
//				$biState = $this->input->post('biState') ;
//				if($this->input->post('hasBiState') == "no") {
//					$biState = $this->input->post('biStateText') ;
//				}
//				
//				$new_address_insert_data = array(
//					'first_name' => $first_last_name[0],
//					'last_name' => $first_last_name[1],		 
//					'street_address_1' =>  $this->input->post('biAddress1'),
//					'street_address_2' => $this->input->post('biAddress2'),
//					'city' => $this->input->post('biCity'),
//					'state' => $biState,
//					'zip_code' => $this->input->post('biZip'),
//					'country' => $this->input->post('biCountry'),			
//					'phone_number' => $this->input->post('biPhone1').$this->input->post('biPhone2'),
//					'phone_extension' => $this->input->post('biPhone3'),		
//					//'email_address'=>  $this->input->post('email')
//				);
//			
//				//insert billing data
//				$insert = $this->db->insert('addresses', $new_address_insert_data);
//				$billing_id = $this->db->insert_id();							
//				//$this->cart->destroy();
//				
//				//load view
//				$content = $this->load->view('shoppingcart_view', $data,true);
//				$content .= $this->load->view('receipt_view', $data,true);
//				$response->content = $content;
			//}
			
			//substract point
			modules::run('pay/exchangePointToItem', $this->session->userdata('id'), $total_point);

			//insert shipping data
			$state = $this->input->post('state') ;
			if($this->input->post('hasState') == "no") {
				$state = $this->input->post('stateText') ;
			}
			$new_address_insert_data = array(
				'first_name' => $this->input->post('firstname'),
				'last_name' => $this->input->post('lastname'),		 
				'street_address_1' =>  $this->input->post('address1'),
				'street_address_2' => $this->input->post('address2'),
				'city' => $this->input->post('city'),
				'state' => $state,
				'zip_code' => $this->input->post('zip'),
				'country' => $this->input->post('country'),			
				'phone_number' => $this->input->post('phone1').$this->input->post('phone2'),
				'phone_extension' => $this->input->post('phone3'),		
				'email_address'=> $this->session->userdata('email')
			);
			$insert = $this->db->insert('addresses', $new_address_insert_data);
			$shipping_id = $this->db->insert_id();
				
			//insert order data
			$order_data = array("shipping_address_id" => $shipping_id,
								"subtotal" => $total_point,
								"total" => ceil($total_point),
								"order_status" => ORDER_ORDERED,
								"shipping" => $shipping_fee,
								"fees" => $total_fee,
								"user_id" => $this->session->userdata('id'),
								//"payment_id" => $response->clientRequestNumber
								);
			$this->db->insert('orders', $order_data);
			$order_id = $this->db->insert_id();
			$order_data = array("access_code" => $this->shoppingcart_model->getOrderAccessCode($order_id));
			$this->db->update('orders', $order_data, array("id" => $order_id));
			
			//insert orderdetail data
			foreach($this->cart->contents() as $item){
				$orderdetail_data = array("order_id" => $order_id,
								"product_id" => $item['id'],
								"product_option_id" => null,
								"quantity" => $item['qty'],
								"point" => $item['point'] * $item['qty']);
				$this->db->insert('orderdetail', $orderdetail_data);
				
				$this->db->set('qty_avail', 'qty_avail - '. $item['qty'], FALSE);
				$this->db->set('qty_sold', 'qty_sold + '. $item['qty'], FALSE);
				$this->db->update('products', null, array("id" => $item['id']));
			}
			$response->success = true;
			$this->cart->destroy();
			
			//email customers
			//$this->shoppingcart_model->sendOrderReceiptEmail($order_id, $this->session->userdata('email'));
			
			//load receipt page
			$data = $this->membership_model->populdateBuyerSignupInfo();
			$this->membership_model->getCreditCardData($data);
//			$data['shippinginfo'] = (object) $new_address_insert_data;
//			$data['order'] = $this->shoppingcart_model->getOrders(array('order_id' => $order_id));
//			$data['orderdetail'] =  $this->shoppingcart_model->getOrderDetails(array('order_id' => $order_id));
//			$content = $this->load->view('shoppingcart_view', $data,true);
			$response->content = '';
			$order_data['id'] = $order_id;
			$response->order_data = $order_data;
		}
		echo json_encode($response);
	}
	
	function clear(){
		$this->cart->destroy();
	}

	function currentCartItem(){
		echo $this->cart->total_items();
	}
	
	function receipt($order_id){
		$this->load->model("shoppingcart_model");
		
		$data['order_id'] = $order_id;
		$data['order'] = $this->shoppingcart_model->getOrders(array('order_id' => $order_id));
		$data['orderdetail'] =  $this->shoppingcart_model->getOrderDetails(array('order_id' => $order_id));
		$content = $this->load->view('receipt_view', $data,true);
		Template::display($content);
	}
	
	function deleteCartItem(){
		$rowid = $this->input->post('rowid');
		$index = 0;
		foreach($this->cart->contents() as $item){
			if($item['rowid'] == $rowid){
				$this->cart->update(array("rowid" => $item['rowid'],
										  "qty" => 0));
				break;
			}
			$index++;
		}
		$this->load->model("model/membership_model");
		$data = $this->membership_model->populdateBuyerSignupInfo();
		$this->membership_model->getCreditCardData($data);
		$content = $this->load->view('shoppingcart_view', $data, true);
		echo $content;
	}
	
	function changeCartItemQty(){
		$rowid = $this->input->post('rowid');
		$qty = $this->input->post('qty');
		foreach($this->cart->contents() as $item){
			if($item['rowid'] == $rowid){
				$this->cart->update(array("rowid" => $item['rowid'],
										  "qty" => $qty));
				break;
			}
		}
		$this->load->model("model/membership_model");
		$data = $this->membership_model->populdateBuyerSignupInfo();
		$this->membership_model->getCreditCardData($data);
		$content = $this->load->view('shoppingcart_view', $data, true);
		echo $content;
	}
	
	function validatephone($phone2=''){
		return modules::run('common/validatephone', $phone2);
	}
   
}

?>